<template>
  <div class="main-layout-1">
    <el-form>
      <el-row :gutter="16" justify="space-between">
        <el-col :span="6">
          <el-form-item>
            <el-input placeholder="输入代码或名称搜索" clearable disabled v-model="keyword"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button disabled @click="filters">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item style="text-align: right;">
            <a href="./source/template.xlsx" download="导入模板">
              <el-button :icon="Download" @click="downloadTemplate">下载模板</el-button>
            </a>

            <el-button style="margin-left: 10px;" :icon="Download" @click="exportData">导出</el-button>
            <el-button :icon="Upload" @click="importData">导入</el-button>
            <el-button :icon="Upload" @click="add">新增</el-button>
            <el-button :icon="DeleteFilled" @click="clearTable">清空</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="vxe-table-box-wrapper">
      <vxe-table
          ref="xTable"
          size="small"
          border
          stripe
          show-header-overflow
          show-overflow
          highlight-hover-row
          height="auto"
          show-footer
          :footer-method="footerMethod"
          :loading="tableData.loading"
          :data="tableData.records"
      >
        <vxe-column type="seq" title="序号" width="50" align="right" fixed="left"></vxe-column>
        <vxe-column field="fundcode" title="代码" min-width="70" sortable fixed="left"></vxe-column>
        <vxe-column field="name" title="名称" min-width="160" sortable fixed="left"></vxe-column>

        <vxe-column field="cypt" title="平台" min-width="70" sortable></vxe-column>
        <vxe-column field="ddje" title="订单金额" align="right" min-width="100" sortable></vxe-column>
        <vxe-column field="sxf" title="手续费" align="right" min-width="70"></vxe-column>
        <vxe-column field="qrjz" title="确认净值" align="right" min-width="80"></vxe-column>
        <vxe-column field="cccbj" title="成本价" align="right" min-width="80" :title-help="{ content: '成本价=订单金额/持有份额' }"></vxe-column>
        <vxe-column field="cyfe" title="持有份额" align="right" min-width="80"></vxe-column>

        <vxe-column field="mrrq" title="买入日期" align="center" min-width="100"></vxe-column>
        <vxe-column field="cyts" title="持有天" align="center" min-width="70"></vxe-column>

        <vxe-colgroup title="估算净值（实时）">
          <vxe-column field="ssje" title="估算金额" align="right" min-width="100"></vxe-column>
          <vxe-column field="gssye" title="收益额" align="right" min-width="100">
            <template #default="{row}">
              <span :style="{ color: row.gssye > 0 ? 'red': 'green' }">{{row.gssye}}</span>
            </template>
          </vxe-column>
          <vxe-column
              field="gssyl"
              title="收益率"
              min-width="100"
              sortable
              align="right"
              :title-help="{ content: '估算收益率=(估算净值-成本价)/成本价' }"
          >
            <template #default="{row}">
              <span :style="{ color: row.gssyl > 0 ? 'red': 'green' }">{{row.gssyl}}%</span>
            </template>
          </vxe-column>
          <vxe-column field="expectWorthDate" title="估值时间" align="center" min-width="140"></vxe-column>
          <vxe-column class-name="flex-direction-column" field="expectWorth" title="估值" align="right" min-width="80">
            <template #default="{ row }">
              <span>{{row.expectWorth?.toFixed(4)}}</span>
              <span :style="{ color: row.expectGrowth > 0 ? 'red': 'green' }">{{row.expectGrowth}}%</span>
            </template>
          </vxe-column>
        </vxe-colgroup>

        <vxe-colgroup title="净值">
          <vxe-column class-name="flex-direction-column" field="netWorth" title="净值" align="right" min-width="80">
            <template #default="{ row }">
              <span>{{row.netWorth?.toFixed(4)}}</span>
              <span :style="{ color: row.dayGrowth > 0 ? 'red': 'green' }">{{row.dayGrowth}}%</span>
            </template>
          </vxe-column>
          <vxe-column field="netWorthDate" title="净值日期" align="center" min-width="100"></vxe-column>

          <vxe-column field="jzje" title="净值金额" align="right" min-width="100"></vxe-column>
          <vxe-column field="jzsye" title="收益额" align="right" min-width="100">
            <template #default="{row}">
              <span :style="{ color: row.jzsye > 0 ? 'red': 'green' }">{{row.jzsye}}</span>
            </template>
          </vxe-column>
          <vxe-column
              field="jzsyl"
              title="收益率"
              min-width="100"
              sortable
              align="right"
              :title-help="{ content: '估算收益率=(净值-成本价)/成本价' }"
          >
            <template #default="{row}">
              <span :style="{ color: row.jzsyl > 0 ? 'red': 'green' }">{{row.jzsyl}}%</span>
            </template>
          </vxe-column>
        </vxe-colgroup>

        <vxe-colgroup title="历史数据">
          <vxe-column :class-name="upAnDown.bind(null, 'lastWeekGrowth')" field="lastWeekGrowth" title="周涨幅" align="right" min-width="80" :formatter="fmtRate"></vxe-column>
          <vxe-column :class-name="upAnDown.bind(null, 'lastMonthGrowth')" field="lastMonthGrowth" title="月涨幅" align="right" min-width="80" :formatter="fmtRate"></vxe-column>
          <vxe-column :class-name="upAnDown.bind(null, 'lastThreeMonthsGrowth')" field="lastThreeMonthsGrowth" title="三月涨幅" align="right" min-width="80" :formatter="fmtRate"></vxe-column>
          <vxe-column :class-name="upAnDown.bind(null, 'lastSixMonthsGrowth')" field="lastSixMonthsGrowth" title="六月涨幅" align="right" min-width="80" :formatter="fmtRate"></vxe-column>
          <vxe-column :class-name="upAnDown.bind(null, 'lastYearGrowth')" field="lastYearGrowth" title="年涨幅" align="right" min-width="80" :formatter="fmtRate"></vxe-column>
        </vxe-colgroup>

        <vxe-column align="center" title="操作" min-width="110" fixed="right">
          <template #default="{ row }">
            <el-space spacer="|">
              <el-link style="font-size: 13px;" type="primary" @click="gotoDetail(row)">详情</el-link>
              <el-link style="font-size: 13px;" type="danger" @click="remove(row)">删除</el-link>
            </el-space>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Table1',
};
</script>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Download, Upload, DeleteFilled, Delete } from '@element-plus/icons'
import axios from 'axios'
import XLSX from 'xlsx'


const KEY = 'cyList'

const todayZoneStamp = +new Date(new Date().toDateString())
const oneDayStamp = 1000 * 60 * 60 * 24
const keepDays = start => {
  return (todayZoneStamp - new Date(start + ' ')) / oneDayStamp
}

const router = useRouter()

const tableData = reactive({
  loading: false,
  records: null,
  modelVisible: false,
})
const xTable = ref()

const queryData = (cyList) => {
  axios.get(`https://api.doctorxiong.club/v1/fund?code=${cyList.map(item => item.fundcode).join()}`).then(async res => {
    console.log(res.data)
    const { code, data } = res.data
    // code String 基金代码
    // name String 基金名称
    // netWorth Number 当前基金单位净值
    // expectWorth Number 当前基金单位净值估算
    // expectGrowth String 当前基金单位净值估算日涨幅,单位为百分比
    // dayGrowth String 单位净值日涨幅,单位为百分比
    // lastWeekGrowth String 单位净值周涨幅,单位为百分比
    // lastMonthGrowth String 单位净值月涨幅,单位为百分比
    // lastThreeMonthsGrowth String 单位净值三月涨幅,单位为百分比
    // lastSixMonthsGrowth String 单位净值六月涨幅,单位为百分比
    // lastYearGrowth String 单位净值年涨幅,单位为百分比
    // netWorthDate String 净值更新日期,日期格式为yy-MM-dd HH:mm.2019-06-27 15:00代表当天下午3点
    // expectWorthDate String 净值估算更新日期,,日期格式为yy-MM-dd HH:mm.2019-06-27 15:00代表当天下午3点

    cyList.forEach((cyItem, index) => {
      const remoteItem = data[index]
      if (cyItem.fundcode === remoteItem.code) {
        const { ddje, cyfe, mrrq } = cyItem
        const { expectWorth, netWorth } = remoteItem

        const cccbj = (ddje/cyfe).toFixed(4)
        const ssje = (cyfe * expectWorth).toFixed(2)
        const jzje = (cyfe * netWorth).toFixed(2)
        Object.assign(cyItem, remoteItem, {
          cccbj,
          cyts: keepDays(mrrq),

          ssje,
          gssye: (ssje - ddje).toFixed(2),
          gssyl: ((expectWorth - cccbj)/cccbj * 100).toFixed(2),

          jzje,
          jzsye: (jzje - ddje).toFixed(2),
          jzsyl: ((netWorth - cccbj)/cccbj * 100).toFixed(2),
        })
      } else {
        throw new Error('对应关系异常！请检查接口数据是否异常。')
      }
    })

    tableData.records = cyList
    tableData.loading = false
  }).catch(err => {
    throw new Error(err)
  })
}

const cyList = JSON.parse(localStorage.getItem(KEY) || '[]')
if (cyList.length) {
  tableData.loading = true
  queryData(cyList)
}

const upAnDown = (property, { row }) => {
  const num = row[property]
  if (num === '') {
    return
  }

  return num > 0 ? 'cell-red' : 'cell-green'
}

const sumNum = (data, property) => (data.reduce((result, item) => result += item[property] * 100, 0) / 100).toFixed(2)
const footerMethod = ({ columns, data }) => {
  const sums: any[] = []
  columns.forEach((column, columnIndex) => {
    if (columnIndex === 0) {
      sums.push('总计')
    } else {
      let sumCell: any = null
      switch (column.property) {
        case 'ddje':
        case 'sxf':
        case 'ssje':
        case 'gssye':
        case 'jzje':
        case 'jzsye':
          sumCell = sumNum(data, column.property)
          break;
        default:
          sumCell = '-'
          break;
      }
      sums.push(sumCell)
    }
  })
  // 返回一个二维数组的表尾合计
  return [sums]
}

const keyword = ref('')
const filters = () => {}

const gotoDetail = (row) => {
  const { fundcode, mrrq, qrjz } = row
  router.push({
    path: `/fundDetail/${fundcode}`,
    query: { mrrq, qrjz },
  })
}

const fmtRate = ({ cellValue }) => {
  return cellValue && cellValue + '%'
}

const exportData = () => {
  xTable.value.exportData({ type: 'csv' })
}
const downloadTemplate = () => {}
const clearTable = () => {
  xTable.value.remove().then(() => {
    localStorage.removeItem(KEY)
  }).catch(err => err)
}

const importData = () => {
  xTable.value.readFile({
    types: ['xls', 'xlsx', 'csv']
  }).then(res => {
    tableData.loading = true
    const fileReader = new FileReader()
    fileReader.onload = (event) => {
      const data = event.target ? event.target.result : ''
      const workbook = XLSX.read(data, { type: 'binary' })
      console.log(workbook)
      const cyList = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1)
      if (cyList.length) {
        queryData(cyList)
        localStorage.setItem(KEY, JSON.stringify(cyList))
      }
    }
    fileReader.readAsBinaryString(res.files[0])
  }).catch(err => {
    throw new Error(err)
  })
}

const add = () => {}
const remove = () => {}

</script>

<style scoped lang='scss'>

</style>
